package com.qmock.pay.http;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Iterator;

/**
 * @author tianqing.wang
 */
public class DefaultXMLResponseParameters implements ResponseParameters {
    private String path;
    public DefaultXMLResponseParameters(String path){
        this.path=path;
    }
    @Override
    public ParameterPairs toPairs() {
        ParameterPairs parameterPairs=new ParameterPairs();
        SAXReader saxReader = new SAXReader();
        try {
            Document document=saxReader.read(new File(this.path));
            document.setXMLEncoding("UTF-8");
            if(document.getRootElement().getName().equals("response")){
				Iterator<Element> iterator = document.getRootElement().elementIterator("parameter");
                while(iterator.hasNext()){
                    Element element=iterator.next();
                    String key = element.attributeValue("key");
                    String value=element.attributeValue("value");
                    parameterPairs.add(key,value);
                }
            }
        } catch (DocumentException e) {
            throw new RuntimeException("没有找到配置的请求参数XML文件,请检查参数文件是否存在",e);
        }
        return parameterPairs;
    }
}
